'use strict';

var zixysSpinner = function(element,$scope, model){
        this.isSpinning = false;
        this.timer;
        this.digitsReg = /^-?[0-9]+(\.[0-9]+)?$/g;
        this.increment = 0;
        this.currentVal = 0;
        this.element = element;
        this.delayInc = 300;
        this.$scope = $scope;
        this.model = model;
        this.min = parseInt(element.attr('min'));
        this.max = parseInt(element.attr('max'));
        
        this.isOutOfRange = function(){return false};
        
        if(!isNaN(this.min) && !isNaN(this.max)){
            this.isOutOfRange = function(x){
                if( (x<this.min) || (x>this.max) ){
                    return true;
                }
                return false;
            }
        }else if(!isNaN(this.min)){
            this.isOutOfRange = function(x){
                if(x<this.min){
                    return true;
                }
                return false;
            }            
        }else if(!isNaN(this.max)){
            this.isOutOfRange = function(x){
                if(x>this.max){
                    return true;
                }
                return false;
            }
        }
}

zixysSpinner.prototype.addUp = function(){
        if(this.isOutOfRange(this.currentVal+this.increment)){
            clearTimeout(this.timer);
            return;
        }
        this.currentVal = this.currentVal+this.increment;
        this.$scope.__temp = this.element[0].value = this.currentVal;
        this.$scope.$eval(this.model+'= __temp');
        delete this.$scope.__temp;
        this.$scope.$apply(this.model);
        this.wait.apply(this);
};

zixysSpinner.prototype.wait = function(){
        var self = this;
        if(this.isSpinning){
            this.timer = setTimeout(function(){
                self.addUp.apply(self);
            },this.delayInc);
            this.delayInc = 10;
        }else{
            clearTimeout(this.timer);
            return;
        }
};

zixysSpinner.prototype.parseValue = function(value){

    if(value.match(this.digitsReg)){
        this.currentVal = parseInt(parseFloat(value*100))/100;
        return true;
    }else{
        this.stop();
        return false;
    }

}

zixysSpinner.prototype.start = function(){
    this.delayInc = 300;
    this.currentVal = '';
    this.parseValue(this.element[0].value);
    this.addUp();
}

zixysSpinner.prototype.stop = function(){
    clearTimeout(this.timer);
    this.isSpinning = false;
    this.currentVal = '';
    this.increment = 0;
}

zixysSpinner.prototype.singleRun = function(){
    
    if(this.parseValue(this.element[0].value)){
        
        if(this.isOutOfRange(this.currentVal)){
           this.$scope.$eval(this.model+'= 0');
        }else{
            this.$scope.__temp = this.element[0].value = this.currentVal;
            this.$scope.$eval(this.model+'= __temp');
            delete this.$scope.__temp;
        }
        this.$scope.$apply(this.model);
    }
}

